package com.eduagent.xwqeduagent.app.student.UniversalLearningAssistant;

import com.eduagent.xwqeduagent.adviser.MyLoggerAdvisor;
import com.eduagent.xwqeduagent.app.agent.GenerateMindMap;
import com.eduagent.xwqeduagent.constant.prompt.GenerateHandoutPrompt;
import com.eduagent.xwqeduagent.constant.prompt.SpeechEvaluationAnalysisSystem;
import com.eduagent.xwqeduagent.constant.prompt.StudentAssistantSystem;
import com.eduagent.xwqeduagent.constant.prompt.TeaMulGenerateSystem;
import com.eduagent.xwqeduagent.model.vo.ImmersiveVideoLearningVO;
import com.eduagent.xwqeduagent.rag.QueryRewriter;
import com.eduagent.xwqeduagent.rag.QueryTranslation;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;


@Component
@Slf4j
public class UniversalLearningAssistant {

    private final ChatClient chatClient;

    @Resource
    private QueryRewriter queryRewriter;

    @Resource
    private QueryTranslation queryTranslation;

    @Resource
    private ToolCallback[] allTools;

    @Resource
    private GenerateMindMap generateMindMap;

    @Resource
    private ToolCallbackProvider toolCallbackProvider;

    @Resource
    private Advisor loveAppRagCloudAdvisor;

    // 缓存视频相关的内容，用于上下文连续对话
    private final Map<String, Map<String, String>> videoContextCache = new HashMap<>();

    public UniversalLearningAssistant(ChatModel dashscopeChatModel) {

        String studentPrompt = StudentAssistantSystem.STUDENT_PROMPT;
        chatClient = ChatClient.builder(dashscopeChatModel)
                .defaultSystem(studentPrompt)
                .defaultAdvisors(
                        //自定义日志Advisor，可以按需开启
                        new MyLoggerAdvisor()
                        //自定义 Re2推理增强 Advisor，可以按需开启
                        //new ReReadingAdvisor(),
                        //new SensitiveWordAdvisor()
                )
                .build();
    }


    /**
     *语音评测分析
     * @param xmlResponse
     * @param sessionId
     * @return
     */
    public String VoiceEvaluationAndAnalysis(String xmlResponse , String sessionId){
        String speechEvaluationPrompt = SpeechEvaluationAnalysisSystem.SPEECH_EVALUATION_PROMPT;

        ChatResponse chatResponse = chatClient
                .prompt()
                .system(speechEvaluationPrompt)
                .user(xmlResponse) // Or use userPrompt if modified
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, sessionId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 20))
                // 开启日志，便于观察效果
                .advisors(new MyLoggerAdvisor())
                .call()
                .chatResponse();
        return chatResponse.getResult().getOutput().getText();
    }

    /**
     * 沉浸式视频学习 - 边看边问
     * 
     * @param question 学生提问（语音转文本或直接文本输入）
     * @param videoTranscript 视频文字稿
     * @param sessionId 会话ID
     * @return 智能解答
     */
    public ImmersiveVideoLearningVO askWhileWatching(String question,
                                                   String videoTranscript,
                                                   String sessionId) {
        // 构建系统提示词
        String systemPrompt = "你是一个沉浸式视频学习助手，帮助学生理解他们正在观看的教育视频。" +
                "基于视频文字稿，为学生提供清晰、准确的解答。" +
                "解释应该简洁明了，突出重点，便于理解。" +
                "如果问题与提供的材料无关，请礼貌地引导回相关内容。" +
                "始终保持友好、专业的教学风格。";
        
        // 构建用户查询，包括当前上下文
        String userQuery = String.format(
                "我正在观看视频，有以下问题：\n\n%s\n\n" +
                "---视频文字稿相关部分---\n%s",
                question, videoTranscript);
        
        log.info("沉浸式学习提问：{}", question);
        
        // 调用AI获取回答
        ChatResponse chatResponse = chatClient
                .prompt()
                .system(systemPrompt)
                .user(userQuery)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, sessionId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 20))
                .advisors(new MyLoggerAdvisor())
                .advisors(loveAppRagCloudAdvisor) // 使用RAG顾问增强回答质量
                .tools(allTools)
                .call()
                .chatResponse();
        
        String answer = chatResponse.getResult().getOutput().getText();
        log.info("沉浸式学习回答生成完成，长度：{}", answer.length());
        
        // 构建返回对象
        ImmersiveVideoLearningVO result = new ImmersiveVideoLearningVO();
        result.setQuestion(question);
        result.setAnswer(answer);
        
        return result;
    }
}
